package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/3
 */
public class Thread_3_两阶段终止模式 {

    public static void main(String[] args) {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tpt.stop();
    }

}

@Slf4j
class TwoPhaseTermination {

    private Thread monitor;

    //启动监控线程

    public void start() {

        monitor = new Thread(() -> {

            while (true) {

                Thread current = Thread.currentThread();

                if (current.isInterrupted()) {

                    log.info("打断标记：{}", current.isInterrupted());

//                  同current.isInterrupted()一样返回打断状态，但是会重置状态
                    Thread.interrupted();

                    log.info("打断标记：{}", current.isInterrupted());

                    log.info("关闭线程前释放相关资源");

                    break;

                }

                try {

                    Thread.sleep(1000);

                    log.info("执行监控记录");
                } catch (InterruptedException e) {
//                    e.printStackTrace();
                    //主要是睡眠情况下，会清除打断标记，所以自己要再打一次
                    current.interrupt();
                }
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop() {
        monitor.interrupt();
    }
}
